package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/rcrowley/go-metrics"
	"github.com/rpcxio/rpcx-etcd/serverplugin"
	"log"
	"net"
	_ "net/http/pprof"
	"runtime"
	"time"

	example "github.com/rpcxio/rpcx-examples"
	"github.com/smallnest/rpcx/server"
)

var (
	addr = flag.String("addr", "localhost:8972", "server address")
)

var clientConn net.Conn
var connected = false

type Arith int
type Arith2 int

func (t *Arith) Mul(ctx context.Context, args *example.Args, reply *example.Reply) error {
	fmt.Println("收到消息······")
	clientConn = ctx.Value(server.RemoteConnContextKey).(net.Conn)
	reply.C = args.A * args.B
	connected = true
	return nil
}

func (t *Arith2) Mul2(ctx context.Context, args *example.Args, reply *example.Reply) error {
	clientConn = ctx.Value(server.RemoteConnContextKey).(net.Conn)
	reply.C = args.A * args.B
	connected = true
	return nil
}

func addRegistryPlugin(s *server.Server, address string) {

	r := &serverplugin.EtcdV3RegisterPlugin{
		ServiceAddress: address,
		EtcdServers:    []string{"localhost:2379"},
		BasePath:       "/rpcx_test",
		Metrics:        metrics.NewRegistry(),
		UpdateInterval: time.Minute,
	}
	err := r.Start()
	if err != nil {
		log.Fatal(err)
	}
	s.Plugins.Add(r)
}

func startServer(address string) {
	s := server.NewServer()
	addRegistryPlugin(s, address)
	//s.RegisterName("Arith", new(example.Arith), "")
	s.Register(new(Arith), "")
	go s.Serve("tcp", address)
}

func startServer2(address string) {
	s := server.NewServer()
	addRegistryPlugin(s, address)
	//s.RegisterName("Arith", new(example.Arith), "")
	s.Register(new(Arith2), "")
	go s.Serve("tcp", address)
}

func main() {
	go startServer("localhost:8972")
	go startServer("localhost:8973")
	go startServer("localhost:8974")
	go startServer("localhost:8975")
	go startServer("localhost:8976")
	go startServer("localhost:8977")

	for {
		runtime.Gosched()
	}
}
